﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;

namespace ResourceReportBuilder
{
    //[ComVisible(true)]
    public partial class OutputForm : Form
    {
        public event EventHandler ReportLoaded;

        private string _reportPath;

        public OutputForm(string reportPath)
        {
            InitializeComponent();
            _reportPath = reportPath;
        }

        private void OutputForm_Load(object sender, EventArgs e)
        {
            this.Activate();
            this.BringToFront();
            if (File.Exists(_reportPath))
            {
                webBrowserResults.Navigate(string.Format("file://{0}", _reportPath));
            }
            else
            {
                MessageBox.Show("Report file does not exist!", "Report Missing", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public virtual void OnReportLoaded()
        {
            EventHandler handler = ReportLoaded;
            if (handler != null)
            {
                foreach (EventHandler singleCast in handler.GetInvocationList())
                {
                    ISynchronizeInvoke syncInvoke = singleCast.Target as ISynchronizeInvoke;
                    try
                    {
                        if (syncInvoke != null && syncInvoke.InvokeRequired)
                        {
                            syncInvoke.Invoke(singleCast, new object[] { this, EventArgs.Empty });
                        }
                        else
                        {
                            singleCast(this, EventArgs.Empty);
                        }
                    }
                    catch
                    { }
                }
            }

        }

        private void webBrowserResults_DocumentCompleted(object sender, EventArgs e)
        {
            if (webBrowserResults.Url.Equals(new Uri(string.Format("file://{0}", _reportPath))))
            {
                OnReportLoaded();
            }
        }
    }
}
